// donation.js
// 获取app实例
const app = getApp();

Page({
  data: {
    donationList: [
      { id: 1, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 2, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 3, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 4, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 5, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 6, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 7, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 8, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 9, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
      { id: 10, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' }
    ],
    scrollTransform: 0,
    scrollTimer: null,
    totalHeaderHeightall: "",
    showcustomerservice: false,
    showmsg: false,
    massges: "",
    // 用户统计数据
    userStats: {
      feedback_count: 0,      // 纠错记录数
      comment_count: 0,       // 评论记录数
      has_completed_quiz: 0,  // 是否完成答题
      total_correct_count: 0  // 总答对题数
    },
    statsLoading: false       // 统计加载状态
  },
  gopai: function () {
    wx.redirectTo({
      url: '/service/xingguang/xingguang'
    });
  },
  onGuanggaoTap: function () {
    wx.redirectTo({
      url: '/pages/index/index'
    });
  },

  goactives: function (e) {
    wx.navigateTo({
      url: '/service/activity/activity'
    });
  },
  getdonationlist: function (e) {
    const that = this;

    // 获取捐赠滚动信息列表
    app.api.getDonationScrollList({
      limit: 20 // 获取20条最新的捐赠记录
    }).then(res => {
      if (res && res.code === 200 && res.data) {
        // 更新捐赠列表数据
        that.setData({
          donationList: res.data
        });

        // 重新启动自动滚动
        that.stopAutoScroll();
        that.startAutoScroll();

        console.log('获取捐赠滚动信息成功:', res.data);
      } else {
        console.error('获取捐赠滚动信息失败:', res);
        // 如果获取失败，使用默认数据
        that.setData({
          donationList: [
            { id: 1, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
            { id: 2, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
            { id: 3, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' }
          ]
        });
      }
    }).catch(err => {
      console.error('获取捐赠滚动信息异常:', err);
      // 如果请求异常，使用默认数据
      that.setData({
        donationList: [
          { id: 1, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
          { id: 2, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' },
          { id: 3, name: '小土豆', action: '完成了爱心捐款，传递了爱心！' }
        ]
      });
    });
  },

  // 获取用户统计数据
  getUserStats: function () {
    const that = this;

    // 设置加载状态
    that.setData({
      statsLoading: true
    });

    // 调用用户统计API
    app.api.getUserStats().then(res => {
      if (res && res.code === 200 && res.data) {
        // 更新用户统计数据
        that.setData({
          userStats: res.data,
          statsLoading: false
        });
        console.log('用户统计数据获取成功:', res.data);
      } else {
        console.error('获取用户统计数据失败:', res);
        that.setData({
          statsLoading: false
        });
      }
    }).catch(err => {
      console.error('获取用户统计数据异常:', err);
      that.setData({
        statsLoading: false
      });
    });
  },
  juank: function (e) {
    if (wx.getStorageSync('jiucuo_records')) {
      // 活动题纠错了
      this.onImageTap()
    } else {
      this.setData({
        showmsg: true,
        massges: "暂无捐款机会",
      });
      setTimeout(() => {
        this.setData({
          showmsg: false,
          massges: "",
        });
      }, 1000);
    }
  },

  onImageTap: function () {
    this.setData({
      showcustomerservice: true
    });
  },

  oncustomerserviceClose: function () {
    this.setData({
      showcustomerservice: false
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.setData({
      totalHeaderHeightall: app.globalData?.totalHeaderHeight
    });

    this.getdonationlist();
    // 获取用户统计数据
    this.getUserStats();
    // 启动自动滚动

    this.startAutoScroll();
  },

  /**
   * 启动自动滚动
   */
  startAutoScroll: function () {
    const that = this;

    // 清理之前的定时器
    if (that.data.scrollTimer) {
      clearInterval(that.data.scrollTimer);
    }

    let currentPosition = 0;
    const itemHeight = 30; // 每行高度
    const totalItems = that.data.donationList.length;

    // 设置新的定时器
    const timer = setInterval(function () {
      currentPosition += 1; // 每次移动1个位置

      // 如果超过了原始列表长度，就回到起点（但用户看不到）
      if (currentPosition > totalItems) {
        // 无动画跳回起点
        that.setData({
          scrollTransform: 0,
          scrollTransition: 0
        });

        // 下一帧开始正常滚动
        setTimeout(() => {
          currentPosition = 1;
          that.setData({
            scrollTransform: -currentPosition * itemHeight,
            scrollTransition: 0.5
          });
        }, 50);
      } else {
        // 正常滚动
        that.setData({
          scrollTransform: -currentPosition * itemHeight,
          scrollTransition: 0.5
        });
      }

    }, 2000); // 每2秒滚动一次

    this.setData({
      scrollTimer: timer
    });
  },


  stopAutoScroll: function () {
    if (this.data.scrollTimer) {
      clearInterval(this.data.scrollTimer);
      this.setData({
        scrollTimer: null
      });
    }
  },
  // 触摸开始，暂停滚动
  onScrollTouchStart: function () {
    this.stopAutoScroll();
  },

  // 触摸结束，恢复滚动  
  onScrollTouchEnd: function () {
    this.startAutoScroll();
  },
  onHide: function () {
    // 页面隐藏时停止滚动
    this.stopAutoScroll();
  },

  onShow: function () {
    // 页面显示时重新开始滚动
    this.startAutoScroll();
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

    // 清理定时器
    this.stopAutoScroll();
  },


  // 打开评论弹窗
  openPinglunModal: function () {
    this.setData({
      showPinglunModal: true
    });
  },

  // 时间格式化函数
  formatTime: function (timestamp) {
    if (!timestamp) return '';

    // 如果是时间戳格式（秒级或毫秒级）
    if (typeof timestamp === 'number' || /^\d+$/.test(timestamp)) {
      // 判断是秒级时间戳还是毫秒级时间戳
      let date;
      if (timestamp > 1000000000000) {
        // 毫秒级时间戳
        date = new Date(parseInt(timestamp));
      } else {
        // 秒级时间戳
        date = new Date(parseInt(timestamp) * 1000);
      }

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 如果是字符串格式，尝试直接返回
    if (typeof timestamp === 'string') {
      // 如果是ISO格式的时间字符串
      if (timestamp.includes('T') && timestamp.includes('Z')) {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 如果已经是格式化的时间字符串，直接返回
      if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(timestamp)) {
        return timestamp;
      }

      // 如果是字符串格式的时间戳
      if (/^\d+$/.test(timestamp)) {
        let date;
        if (timestamp.length > 10) {
          // 毫秒级时间戳
          date = new Date(parseInt(timestamp));
        } else {
          // 秒级时间戳
          date = new Date(parseInt(timestamp) * 1000);
        }

        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }

    // 其他情况返回原始值
    return timestamp;
  },

  // 加载评论列表
  loadCommentList: function () {
    const that = this;
    const { questionId, commentPage, commentLimit } = this.data;

    if (!questionId) {
      return;
    }

    // 设置加载状态
    this.setData({
      commentLoading: true
    });

    // 调用API获取评论列表
    app.api.getCommentList({
      questionId: questionId,
      page: commentPage,
      limit: commentLimit
    }).then(res => {
      if (res && res.code === 200 && res.data) {
        const commentData = res.data;

        // 格式化评论数据
        const formattedComments = commentData.data.map(comment => ({
          id: comment.id,
          content: comment.content,
          likeCount: comment.like_count || 0,
          createTime: that.formatTime(comment.created_at),
          user: comment.user || {
            id: 0,
            nickname: '匿名用户',
            avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
          }
        }));
        console.log(commentData.data)
        let answerRecords = JSON.parse(JSON.stringify(this.data.answerRecords))
        console.log(answerRecords)
        console.log(this.data.currentBannerIndex)
        answerRecords[this.data.currentBannerIndex].commentList = formattedComments
        console.log(answerRecords)
        that.setData({
          answerRecords: answerRecords,
          commentList: formattedComments,
          commentTotal: commentData.total || 0,
          commentLoading: false
        });
        console.log(this.data.answerRecords)
      } else {
        that.setData({
          commentLoading: false
        });
      }
    }).catch(err => {
      console.error('加载评论列表失败:', err);
      that.setData({
        commentLoading: false
      });

      // 如果加载失败，显示默认评论数据
      that.setDefaultCommentData();
    });
  },

  // 设置默认评论数据
  setDefaultCommentData: function () {
    const defaultComments = [
      {
        id: 1,
        content: '这道题很有代表性，考察了核心知识点',
        likeCount: 5,
        createTime: '2024-01-15 10:30:00',
        user: {
          id: 1,
          nickname: '学习达人',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      },
      {
        id: 2,
        content: '选项C的干扰性很强，容易选错',
        likeCount: 3,
        createTime: '2024-01-14 15:20:00',
        user: {
          id: 2,
          nickname: '学霸小张',
          avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
        }
      }
    ];

    this.setData({
      commentList: defaultComments,
      commentTotal: defaultComments.length
    });
  },

  // 关闭评论弹窗
  closePinglunModal: function () {
    this.setData({
      showPinglunModal: false
    });
  },

  // 处理评论提交
  handlePinglunSubmit: function (e) {
    const { content, commentId } = e.detail;
    console.log('收到评论内容:', content, '评论ID:', commentId);

    // 评论组件已经调用了API，这里只需要重新加载评论列表显示最新评论
    const questionId = this.data.questionId || this.data.currentQuestionId;
    this.loadCommentList(questionId);
  },

  // 点赞评论
  likeComment: function (e) {
    const commentId = e.currentTarget.dataset.commentId;
    const questionId = this.data.questionId || this.data.currentQuestionId;
    const that = this;

    if (!commentId || !questionId) {
      return;
    }

    // 调用API点赞评论
    app.api.likeComment({
      commentId: commentId
    }).then(res => {
      if (res && res.code === 200) {
        // 点赞成功，更新本地评论列表
        const questionIndex = that.data.answerRecords.findIndex(record => record.questionId === questionId);
        if (questionIndex !== -1 && that.data.answerRecords[questionIndex].commentList) {
          const newAnswerRecords = [...that.data.answerRecords];
          newAnswerRecords[questionIndex].commentList = newAnswerRecords[questionIndex].commentList.map(comment => {
            if (comment.id === commentId) {
              return {
                ...comment,
                likeCount: comment.likeCount + 1
              };
            }
            return comment;
          });

          that.setData({
            answerRecords: newAnswerRecords
          });
        }

        wx.showToast({
          title: '点赞成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '点赞失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('点赞评论失败:', err);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
  },

  // 处理wenda组件发表评论
  handleWendaPublishComment: function (e) {
    const { content, messageIndex } = e.detail;
    const currentIndex = this.data.currentBannerIndex;

    if (currentIndex === undefined || currentIndex < 0) {
      wx.showToast({
        title: '当前题目索引错误',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查当前索引是否在answerRecords范围内
    if (currentIndex >= this.data.answerRecords.length) {
      wx.showToast({
        title: '题目索引超出范围',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 创建新评论对象
    const newComment = {
      id: Date.now(), // 使用时间戳作为临时ID
      content: content,
      likeCount: 0,
      createTime: this.formatTime(new Date()),
      user: {
        id: 0, // 默认用户ID
        nickname: 'AI助手',
        avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
      }
    };

    // 更新answerRecords中的评论列表
    const newAnswerRecords = [...this.data.answerRecords];
    if (!newAnswerRecords[currentIndex].commentList) {
      newAnswerRecords[currentIndex].commentList = [];
    }
    newAnswerRecords[currentIndex].commentList.unshift(newComment); // 添加到评论列表开头

    // 更新显示评论状态
    const showComments = { ...this.data.showComments };
    showComments[currentIndex] = true;

    this.setData({
      answerRecords: newAnswerRecords,
      showComments: showComments
    });
  },

  /**
   * 处理纠错提交
   */
  handleJiucuoSubmit: function () {
    if (!this.data.feedbackContent.trim()) {
      wx.showToast({
        title: '请输入纠错内容',
        icon: 'none'
      });
      return;
    }

    const that = this;
    app.api.submitFeedback({
      questionId: this.data.questionId,
      content: this.data.feedbackContent
    }).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
      // 清空内容并关闭弹窗
      that.setData({
        feedbackContent: '',
        showJiucuoModal: false
      });
    }).catch(err => {
      console.error('提交纠错失败:', err);
    });
  },

  /**
   * 输入纠错内容
   */
  onFeedbackInput: function (e) {
    this.setData({
      feedbackContent: e.detail.value
    });
  },

  /**
   * 重做功能
   */
  redoQuestion: function () {
    // 重置答题状态
    this.setData({
      selectedOption: null,
      selectedOptions: [],
      isAnswered: false,
      isCorrect: false,
      userAnswer: null,
      submitButtonText: this.data.questionTypeCode <= 1 ? '提交答案' : '显示答案'
    });
    console.log('重做题目');
  },

  /**
   * 格式化时间
   */
  formatTime: function (date) {
    if (!date) return '';

    // 如果是时间戳或字符串，转换为Date对象
    if (typeof date === 'number' || typeof date === 'string') {
      date = new Date(date);
    }

    // 检查是否为有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return '';
    }

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  /**
   * 简单的Markdown解析函数 - 处理标题、加粗和换行
   */
  parseMarkdown: function (text) {
    if (!text) return '';

    let parsed = text;

    // 将 ### 标题 转换为 <h3>标题</h3>
    parsed = parsed.replace(/###\s+(.*?)(?=\n|$)/g, '<h3>$1</h3>');

    // 将 **文本** 转换为 <strong style="color: #9b1e23;">文本</strong>
    parsed = parsed.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #9b1e23;">$1</strong>');

    // 将 \n 转换为 <br/>
    parsed = parsed.replace(/\n/g, '<br/>');

    return parsed;
  },

  /**
   * 调用AI问答接口
   */
  callAIChat: function (message) {
    const that = this;

    // 创建AI消息对象（用于流式传输）- 直接显示"正在思考中..."
    const aiMessage = {
      type: 'ai',
      content: '正在思考中...',
      parsedContent: '正在思考中...',
      time: that.formatTime(new Date()),
      isStreaming: true // 标记为流式传输中
    };

    // 先将AI消息添加到消息列表
    that.setData({
      messages: [...that.data.messages, aiMessage]
    }, () => {
      // 滚动到底部
      that.scrollToBottom();
    });

    const app = getApp();
    wx.request({
      url: app.globalData.baseUrl + '/frontend/ai/chat',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('userToken') || ''
      },
      timeout: 60000, // 设置60秒超时时间
      data: {
        message: message,
        questionId: this.data.questionId,
        isFirstQuestion: this.data.isFirstQuestion ? 1 : 0,
        stream: 1 // 启用流式传输
      },
      success: function (res) {
        if (res.data.code === 200) {
          // 模拟流式效果：逐字显示内容
          const fullContent = res.data.data.content || '';
          const messages = that.data.messages;
          const lastIndex = messages.length - 1;

          // 延迟一小段时间后开始显示真实内容（让用户看到"正在思考中..."）
          setTimeout(() => {
            // 模拟逐字显示效果
            let currentIndex = 0;
            const typingInterval = setInterval(() => {
              if (currentIndex < fullContent.length) {
                const currentContent = fullContent.substring(0, currentIndex + 1);
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  content: currentContent,
                  parsedContent: that.parseMarkdown(currentContent)
                };

                that.setData({
                  messages: messages
                }, () => {
                  that.scrollToBottom();
                });

                currentIndex++;
              } else {
                clearInterval(typingInterval);

                // 流式传输完成
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  isStreaming: false
                };

                that.setData({
                  messages: messages,
                  isLoading: false,
                  isFirstQuestion: false
                });
              }
            }, 30); // 每30ms显示一个字符
          }, 500);
        } else {
          // 处理错误情况
          const messages = that.data.messages;
          messages[messages.length - 1] = {
            ...messages[messages.length - 1],
            content: res.data.message || '服务器错误，请稍后重试',
            parsedContent: res.data.message || '服务器错误，请稍后重试',
            isStreaming: false
          };

          that.setData({
            messages: messages,
            isLoading: false
          });
        }
      },
      fail: function (error) {
        console.error('AI聊天请求失败:', error);

        const messages = that.data.messages;
        messages[messages.length - 1] = {
          ...messages[messages.length - 1],
          content: '网络错误，请检查网络连接后重试',
          parsedContent: '网络错误，请检查网络连接后重试',
          isStreaming: false
        };

        that.setData({
          messages: messages,
          isLoading: false
        });
      }
    });
  },

  /**
   * 滚动到底部
   */
  scrollToBottom: function () {
    wx.createSelectorQuery().select('.ulss').boundingClientRect((rect) => {
      if (rect) {
        wx.createSelectorQuery().select('.ulss').scrollOffset((res) => {
          wx.createSelectorQuery().select('.ulss').context((context) => {
            context.context.scrollTo({
              scrollTop: res.scrollTop + rect.height + 100,
              duration: 300
            });
          }).exec();
        }).exec();
      }
    }).exec();
  },

  /**
   * 输入框内容变化
   */
  onInputChange: function (e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  /**
   * 发送消息
   */
  sendMessage: function (e) {
    const jiexi = e.currentTarget.dataset.jiexi || '';
    if (!jiexi) {
      wx.showToast({
        title: '题目信息加载中',
        icon: 'none'
      });
      return;
    }

    const message = "解析下这个题目：" + jiexi;

    // 重置消息列表，只保留当前解析
    this.setData({
      messages: []
    });

    this.setData({
      isLoading: true,
      inputValue: ''
    });

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: message,
      time: this.formatTime(new Date())
    };

    this.setData({
      messages: [...this.data.messages, userMessage]
    }, () => {
      // 滚动到底部显示用户消息
      this.scrollToBottom();
    });

    // 调用AI问答接口
    this.callAIChat(message);
  }
});
